import React, { useState, useEffect } from 'react';
import { Outlet, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import { message } from 'antd';
import axios from 'axios';
// import Menus from '@/pages/Menus/MenuNav';
// import Dashboard from '@/pages/Dash/DashboardNav';
// import Tutorial from '@/pages/Tutorial/TutorialNav';
// import Users from '@/pages/Users/UsersNav';
// import Roles from '@/pages/Roles/RolesNav';

import {
  DashboardOutlined,
  ProductOutlined,
  KeyOutlined,
  HomeOutlined,
  TeamOutlined,
  UserOutlined,
  ReadOutlined,
  LogoutOutlined,
  DownOutlined
} from '@ant-design/icons';
import { Breadcrumb, Layout, Menu, Popconfirm, theme, Dropdown, Space, Button } from 'antd';
const { Content, Sider } = Layout;

const AuthLayout = () => {

  const [menuData, setMenuData] = useState([]);
  const [expandedRowData, setExpandedRowData] = useState({});
  const [selectedKey, setSelectedKey] = useState('/dashboard');

  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const fetchData = async () => {
        try {
            const response = await axios.get('/menu/list');
            if(response.data.code === 1){
              setMenuData(response.data.menuData);
              setExpandedRowData(response.data.expandedRowData);
          } else {
              console.error('获取菜单数据失败');
          }
        } catch (error) {
            console.error('获取菜单数据失败', error);
        }
    };
  
    fetchData();
  }, []);

  // 反向高亮
  console.log(location.pathname);
  useEffect(() => {
    setSelectedKey(location.pathname);
  }, [location]);
  
  const buildMenuItems = (menuData, expandedRowData) => {
    return menuData.map(item => {
        if (!item.ifshow) return null;
        const children = expandedRowData[item.key]
            ? expandedRowData[item.key].map(subItem => {
                if (!subItem.ifshow) return null;
                return (
                    <Menu.Item key={subItem.nameshow} icon={<ProductOutlined />}>
                        {subItem.name}
                    </Menu.Item>
                );
            }).filter(subItem => subItem !== null)
            : null;
        
        return children && children.length > 0 ? (
            <Menu.SubMenu key={item.nameshow} icon={<KeyOutlined />} title={item.name}>
                {children}
            </Menu.SubMenu>
        ) : (
            <Menu.Item key={item.nameshow} icon={<UserOutlined />}>
                {item.name}
            </Menu.Item>
        );
    }).filter(item => item !== null);
  };
  
  const fixedItems = [
    {
        key: 'sub1',
        icon: <HomeOutlined />,
        title: '首页',
        children: [
            { key: '/dashboard', icon: <DashboardOutlined />, title: '仪表盘' },
            { key: '/tutorial', icon: <ReadOutlined />, title: '使用教程' }
        ]
    }
  ];

  const dynamicItems = buildMenuItems(menuData, expandedRowData);

  const renderMenuItems = (items) => {
    return items.map(item => {
        if (item.children) {
            return (
                <Menu.SubMenu key={item.key} icon={item.icon} title={item.title}>
                    {renderMenuItems(item.children)}
                </Menu.SubMenu>
            );
        } else {
            return (
                <Menu.Item key={item.key} icon={item.icon} onClick={() => navigate(item.key)}>
                    {item.title}
                </Menu.Item>
            );
        }
    });
  };

  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 对用户是否登录进行鉴权
  const protectedRoutes = ['/', '/dashboard', '/tutorial', '/roles', '/menus', '/users'];
  useEffect(() => {
    const isLoggedIn = localStorage.getItem('isLoggedIn');

    if (!isLoggedIn && protectedRoutes.includes(location.pathname)) {
      message.warning('请先登录');
      navigate('/login');
    } else if (isLoggedIn && location.pathname === '/') {
      navigate('/dashboard');
    }
  }, [navigate, location]);

  // 菜单栏点击页面跳转
  const onMenuClick = (route) => {
    const path = route.key;
    navigate(path);
  }

  // 处理点击首页和退出
  const handleHomeClick = () => {
    navigate('/dashboard');
  };
  
  const handleLogoutConfirm = () => {
    // 处理退出逻辑，比如清除用户信息，跳转到登录页面等
    localStorage.removeItem('isLoggedIn');
    console.log(localStorage);
    message.success('已退出登录');
    navigate('/login');
  };

  const userMenu = {
    items: [
      {
        label: <Button onClick={handleHomeClick}>首页</Button>,
        key: '0',
      },
      {
        label: (
          <Popconfirm
            title="是否确认退出？"
            onConfirm={handleLogoutConfirm}
            okText="退出"
            cancelText="取消"
          >
            <Button >退出</Button>
          </Popconfirm>
        ),
        key: '1',
      },
    ],
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider 
              style={{ height: 'calc(100vh)', overflowY: 'auto'}} >
        <div className="sider-vertical" />
        <Menu 
          theme="dark" 
          selectedKeys={[selectedKey]} 
          defaultSelectedKeys={['/dashboard']}
          onClick={onMenuClick}
          mode="inline" 
        >
          {renderMenuItems(fixedItems)}
          {/* {renderMenuItems(dynamicItems)} */}
          {dynamicItems}
        </Menu>
      </Sider>

      <Layout style={{ height: 'calc(100vh)', overflowY: 'auto' }}>
        <Content style={{ margin: '0 16px' }}>
          <div className='content-container'
            style={{
              padding: 24,
              minHeight: 600,
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
            }}
          >
          <div className='user-info' style={{ float:'right' }}>
            <Dropdown menu={userMenu} trigger={['click']}>
              <Button type="link" onClick={(e) => e.preventDefault()}>
                <Space>
                  username
                  <DownOutlined />
                </Space>
              </Button>
            </Dropdown>
          </div>
            {/* 二级路由出口 */}
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default AuthLayout;